<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin','admin',0);

class formguide_info extends admin {
	
	private $db, $f_db, $tablename;
	public function __construct() {
		parent::__construct();
		$this->db = pc_base::load_model('sitemodel_field_model');
		$this->f_db = pc_base::load_model('sitemodel_model');
		if (isset($_GET['formid']) && !empty($_GET['formid'])) {
			$formid = intval($_GET['formid']);
			$f_info = $this->f_db->get_one(array('modelid'=>$formid, 'siteid'=>$this->get_siteid()), 'tablename');
			$this->tablename = 'form_'.$f_info['tablename'];
			$this->db->change_table($this->tablename);
		}
	}
	
	/**
	 * 用户提交表单信息列表
	 */
	public function init() {
		if (!isset($_GET['formid']) || empty($_GET['formid'])) {
			showmessage(L('illegal_operation'), HTTP_REFERER);
		}
		$formid = intval($_GET['formid']);
		if (!$this->tablename) {
			$f_info = $this->f_db->get_one(array('modelid'=>$formid, 'siteid'=>$this->get_siteid()), 'tablename');
			$this->tablename = 'form_'.$f_info['tablename'];
			$this->db->change_table($this->tablename);
		}
		$page = max(intval($_GET['page']), 1);
		$r = $this->db->get_one(array(), "COUNT(dataid) sum");
		$total = $r['sum'];
		$this->f_db->update(array('items'=>$total), array('modelid'=>$formid));
		$pages = pages($total, $page, 20);
		$offset = ($page-1)*20;
		$datas = $this->db->select(array(), '*', $offset.', 20', '`dataid` DESC');
		$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=formguide&c=formguide&a=add\', title:\''.L('formguide_add').'\', width:\'700\', height:\'500\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('formguide_add'));
		include $this->admin_tpl('formguide_info_list');
	}
	
	/**
	 * 查看
	 */
	public function public_view() {
		if (!$this->tablename || !isset($_GET['did']) || empty($_GET['did'])) showmessage(L('illegal_operation'), HTTP_REFERER);
		$did = intval($_GET['did']);
		$formid = intval($_GET['formid']);
		$info = $this->db->get_one(array('dataid'=>$did));
		$views = intval($info['views'])+1;
		$this->db->update(array("views"=>$views),array('dataid'=>$info['dataid']));
		pc_base::load_sys_class('form', '', '');
		define('CACHE_MODEL_PATH',PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_model'.DIRECTORY_SEPARATOR.'caches_data'.DIRECTORY_SEPARATOR);
		require CACHE_MODEL_PATH.'formguide_output.class.php';
		$formguide_output = new formguide_output($formid);
		$forminfos_data = $formguide_output->get($info);
		$fields = $formguide_output->fields;
		include $this->admin_tpl('formguide_info_view');
	}
	
	/**
	 * 删除
	 */
	public function public_delete() {
		$formid = intval($_GET['formid']);
		if (isset($_GET['did']) && !empty($_GET['did'])) {
			$did = intval($_GET['did']);
			$this->db->delete(array('dataid'=>$did));
			$this->f_db->update(array('items'=>'-=1'), array('modelid'=>$formid));
			showmessage(L('operation_success'), HTTP_REFERER);
		} else if(is_array($_POST['did']) && !empty($_POST['did'])) {
			foreach ($_POST['did'] as $did) {
				$did = intval($did);
				$this->db->delete(array('dataid'=>$did));
				$this->f_db->update(array('items'=>'-=1'), array('modelid'=>$formid));
			}
			showmessage(L('operation_success'), HTTP_REFERER);
		} else {
			showmessage(L('illegal_operation'), HTTP_REFERER);
		}
	}
	
	/**
	 * 快速审核
	 */
	public function changeStatus() {
		$dataid = intval($_GET['dataid']);
		if(!$dataid) showmessage(L('missing_part_parameters'));
		$info = $this->db->get_one(array('dataid'=>$dataid));
		if($info){
			$views = $info['views'] + 1;
			$this->db->update(array("views"=>$views),array('dataid'=>$info['dataid']));
			$res = array(
				'status'=>$status,
				'code'=>'ok'
			);
		}else{
			$res = array(
				'status'=>'',
				'code'=>'erroe'
			);
		}
		echo json_encode($res);
	}

	/*
	 * 表单导出
	 */
	public function export(){
		$formid = intval($_GET['formid']);
		$siteid = $this->get_siteid();
		//$objPHPExcel = pc_base::load_sys_class('PHPExcel');
		// $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
		require PC_PATH.'libs/classes/PHPExcel.class.php';
        require PC_PATH.'libs/classes/PHPExcel/Writer/Excel5.php';
        require PC_PATH.'libs/classes/PHPExcel/Writer/Excel2007.php';
        require PC_PATH.'libs/classes/PHPExcel/IOFactory.php';
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("ctos")
                    ->setLastModifiedBy("ctos")
                    ->setTitle("Office 2007 XLSX Test Document")
                    ->setSubject("Office 2007 XLSX Test Document")
                    ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                    ->setKeywords("office 2007 openxml php")
                    ->setCategory("Test result file");

        //set width 
        $objPHPExcel->getActiveSheet()->getColumnDimension()->setWidth(8);
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(8);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);

        //设置默认行高
        $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(35);
        // $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(22);
        // $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
        // 设置垂直居中
        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

        // 设置水平居中
        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        //设置填充颜色
        $objPHPExcel->getActiveSheet()->getStyle('A1:Z1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A1:Z1')->getFill()->getStartColor()->setRGB('1fbb7d');
	   
	    /*设置字体颜色*/
	    $objPHPExcel->getActiveSheet()->getStyle('A1:Z1')->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_WHITE);
	    //冻结第一行
		$objPHPExcel->getActiveSheet()->freezePane('A2');

        //文字加粗
        // $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
        // $objPHPExcel->getActiveSheet()->getStyle('A2:J2')->getFont()->setBold(true);

        // $objPHPExcel->getActiveSheet()->getStyle('A2:J2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        // $objPHPExcel->getActiveSheet()->getStyle('A2:J2')->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

        $this->db = pc_base::load_model('sitemodel_field_model');

        $f_info = $this->f_db->get_one(array('modelid'=>$formid, 'siteid'=>$this->get_siteid()));
        $list = $this->db->select('','*');

        //设置表头
        $ziduan = $this->db->get_fields();
        $a = 0;
        foreach ($ziduan as $k => $z) {
        	$title = $this->getTitle($k);//获取中文名称
        	$objPHPExcel->setActiveSheetIndex(0)->setCellValue($this->azcode($a,1), $title);
        	$objPHPExcel->getActiveSheet()->getStyle($this->azcode($a,1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        	$a++;
        }
        //设置水平居中  
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

        //写入表 
        for ($i =0; $i < count($list); $i++) {
        	$a = 0;
        	$list[$i]['datetime'] = date('Y-m-d H:i:s',$list[$i]['datetime']);
        	foreach ($ziduan as $k => $z) {
	        	$objPHPExcel->setActiveSheetIndex(0)->setCellValue($this->azcode($a,$i + 2), $list[$i][$k]);
	        	$a++;
	        }
        }

        // Rename sheet  
        $objPHPExcel->getActiveSheet()->setTitle($f_info['name'].date('Y-m-d',time()).rand(1000,9999));

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet  
        $objPHPExcel->setActiveSheetIndex(0);

        // Redirect output to a client’s web browser (Excel5)  
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$f_info['name'].date('Ymd').rand(1000,9999).'.xls"');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

	}

	public function getTitle($keyname){
		$defaultFields = array('dataid'=>'ID','userid'=>'用户ID','datetime'=>'录入时间','ip','views'=>'查看次数','username'=>'用户名');
		if(array_key_exists($keyname,$defaultFields)){
			return $defaultFields[$keyname];
		}else{
			$db = pc_base::load_model('sitemodel_field_model');
			$db->change_table('model_field');
			$info = $db->get_one(array("modelid"=>$_GET['formid'],'field'=>$keyname),'name');
			if($info){
				return $info['name'];
			}
		}
		return L($keyname);
	}

	/**
	* 大写英文字母递增
	*
	* chr() 函数从指定的 ASCII 值返回字符
	* ord() 函数返回字符串第一个字符的 ASCII 值
	*
	* @param string $str A-Z的英文字母
	* @return string
	*/
	public function azcode($num,$num2=1){
		$str = $num + 65;
		if ($str >= 90 && $str < 116) {
			$str = $str - 26;
			return 'A'.strtoupper(chr($str)).$num2;
		}else if($str >= 116 && $str < 142){
			$str = $str - 52;
			return 'B'.strtoupper(chr($str)).$num2;
		}else if($str >= 142 && $str < 168){
			$str = $str - 52;
			return 'C'.strtoupper(chr($str)).$num2;
		}else{
			return strtoupper(chr($str)).$num2;
		}
	}
}
?>